package cn.zhxu.toys.captcha.impl;

import cn.zhxu.toys.captcha.CaptchaAttrs;
import cn.zhxu.toys.captcha.CaptchaException;
import cn.zhxu.toys.captcha.CodeRenderer;
import cn.zhxu.toys.msg.MsgSender;
import cn.zhxu.toys.msg.SendResult;

/**
 * @author Troy.Zhou @ 2022/8/16 14:18
 */
public class MsgCodeRenderer implements CodeRenderer {

    public static final String ATTR_PHONE = "phone";
    public static final String ATTR_MSG_TMPL_NAME = "msgTmplName";

    /**
     * 信息发送器
     */
    private MsgSender msgSender;

    /**
     * 验证码信息模板名称
     */
    private String msgTmplName;

    @Override
    public void render(String code, CaptchaAttrs attrs) throws CaptchaException {
        String phone = attrs.require(ATTR_PHONE, String.class);
        String tmplName = attrs.get(ATTR_MSG_TMPL_NAME, String.class, msgTmplName);
        SendResult result = msgSender.send(phone, tmplName, code);
        if (!result.isOk()) {
            throw new CaptchaException("短信验证码发送失败：" + result.getMsg());
        }
    }

    public MsgSender getMsgSender() {
        return msgSender;
    }

    public void setMsgSender(MsgSender msgSender) {
        this.msgSender = msgSender;
    }

    public String getMsgTmplName() {
        return msgTmplName;
    }

    public void setMsgTmplName(String msgTmplName) {
        this.msgTmplName = msgTmplName;
    }

}
